package undestiny.gsondemo;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;


/**
 * 继承Application接口后项目启动时会按照执行顺序执行run方法
 * 通过设置Order的value来指定执行的顺序
 */
@Component
@Order(value = 1)
@Slf4j
public class StartService implements ApplicationRunner {

    @Resource(name = "myGson")
    Gson gson;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        log.info("普通实体的序列化与反序列化：");
        List<String> educationList = new ArrayList<>();
        educationList.add("中国小学");
        educationList.add("上海中学");
        Student student = new Student(1,null,educationList,new Timestamp(System.currentTimeMillis()));

        String studentJSON = gson.toJson(student);
        log.info("  序列化结果：" + studentJSON);

        student = gson.fromJson(studentJSON,Student.class);
        log.info("  反序列化结果：" + "id=" + student.getId());



        log.info("数据集合的序列化与反序列化：");
        List<Student> studentList = new ArrayList<>();
        studentList.add(student);
        Student student1 = new Student(2,"Peter",educationList,new Timestamp(System.currentTimeMillis()));
        studentList.add(student1);

        String studentListJSON = gson.toJson(studentList);
        log.info("  序列化结果：" + studentListJSON);


        Type studentListType = new TypeToken<ArrayList<Student>>(){}.getType();
        studentList = gson.fromJson(studentListJSON, studentListType);

        log.info("  反序列化结果：" + "id=" + studentList.get(0).getId() + "," + studentList.get(1).getId());


    }


}